package a10_动态规划;

/**
 * <p>
 * a53_最长回文子序列复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/5/19
 */
public class a53_最长回文子序列复习3 {
    //dp[i][j]:从i到j的最长子序列为dp[i][j]

    //递推公式：
    //if(chars[i] == chars[j])
    // dp[i][j] = dp[i+1][j-1] + 2;
    //else
    // dp[i][j] = Math.max(dp[i+1][j],dp[i][j-1])

    //遍历方向
    //左下
    //下面
    //左
    public int longestPalindromeSubseq(String s) {
        char[] chars = s.toCharArray();

        int[][] dp = new int[chars.length][chars.length];

        for (int i = chars.length; i >= 0; i--) {
            for (int j = i; j < chars.length; j++) {
                if(chars[i] == chars[j]){
                    if(j == i){
                        dp[i][j] = 1;
                    }else {
                        dp[i][j] = dp[i+1][j-1] + 2;
                    }
                }else {
                    dp[i][j] = Math.max(dp[i+1][j],dp[i][j-1]);
                }
            }
        }
        return dp[0][chars.length-1];
    }
}
